import React, { useState, useMemo } from 'react';
import RuleDetailModal from '../shared/RuleDetailModal';
import {
  List,
  Card,
  Tag,
  Button,
  Space,
  Typography,
  Empty,
  Input,
  Select,
  Row,
  Col,
  Avatar,
  Tooltip,
  Badge
} from 'antd';
import {
  BugOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  EnvironmentOutlined,
  CodeOutlined,
  BulbOutlined,
  RobotOutlined,
  SettingOutlined,
  DatabaseOutlined,
  ThunderboltOutlined,
  SwapOutlined
} from '@ant-design/icons';
import { CompatibilityIssue, SeverityLevel, AnalysisSource, ProblemCategory } from '../../types/analysis';
import './ProblemList.css';

const { Text, Paragraph } = Typography;
const { Search } = Input;
const { Option } = Select;

interface ProblemListProps {
  issues: CompatibilityIssue[];
  onIssueClick?: (issue: CompatibilityIssue) => void;
  analysisSource?: AnalysisSource;
  showLineNumbers?: boolean;
  enableFiltering?: boolean;
  enableSorting?: boolean;
  maxHeight?: number;
}

const ProblemList: React.FC<ProblemListProps> = ({
  issues,
  onIssueClick,
  analysisSource,
  showLineNumbers = true,
  enableFiltering = true,
  enableSorting = true,
  maxHeight = 500
}) => {
  const [searchText, setSearchText] = useState('');
  const [selectedSeverity, setSelectedSeverity] = useState<SeverityLevel | 'ALL'>('ALL');
  const [selectedCategory, setSelectedCategory] = useState<ProblemCategory | 'ALL'>('ALL');
  const [sortBy, setSortBy] = useState<'severity' | 'line' | 'category'>('severity');
  
  // 规则详情模态框状态
  const [ruleDetailVisible, setRuleDetailVisible] = useState(false);
  const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null);

  // 获取严重程度图标和颜色
  const getSeverityIcon = (severity: SeverityLevel) => {
    switch (severity) {
      case 'HIGH':
        return { icon: <BugOutlined />, color: '#ff4d4f' };
      case 'MEDIUM':
        return { icon: <ExclamationCircleOutlined />, color: '#faad14' };
      case 'LOW':
        return { icon: <InfoCircleOutlined />, color: '#1890ff' };
      case 'INFO':
        return { icon: <CheckCircleOutlined />, color: '#52c41a' };
      default:
        return { icon: <InfoCircleOutlined />, color: '#666' };
    }
  };

  // 获取严重程度的权重（用于排序）
  const getSeverityWeight = (severity: SeverityLevel): number => {
    switch (severity) {
      case 'HIGH': return 4;
      case 'MEDIUM': return 3;
      case 'LOW': return 2;
      case 'INFO': return 1;
      default: return 0;
    }
  };

  // 获取分类图标
  const getCategoryIcon = (category: ProblemCategory) => {
    switch (category) {
      case 'SYNTAX':
        return <CodeOutlined />;
      case 'FUNCTION':
        return <SettingOutlined />;
      case 'DATATYPE':
        return <DatabaseOutlined />;
      case 'PERFORMANCE':
        return <ThunderboltOutlined />;
      case 'COMPATIBILITY':
        return <SwapOutlined />;
      default:
        return <InfoCircleOutlined />;
    }
  };

  // 过滤和排序逻辑
  const filteredAndSortedIssues = useMemo(() => {
    let filtered = issues;

    // 文本搜索过滤
    if (searchText) {
      filtered = filtered.filter(issue => 
        issue.ruleName.toLowerCase().includes(searchText.toLowerCase()) ||
        issue.description.toLowerCase().includes(searchText.toLowerCase()) ||
        issue.suggestion.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    // 严重程度过滤
    if (selectedSeverity !== 'ALL') {
      filtered = filtered.filter(issue => issue.severity === selectedSeverity);
    }

    // 分类过滤
    if (selectedCategory !== 'ALL') {
      filtered = filtered.filter(issue => issue.category === selectedCategory);
    }

    // 排序
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'severity':
          return getSeverityWeight(b.severity) - getSeverityWeight(a.severity);
        case 'line':
          return a.lineNumber - b.lineNumber;
        case 'category':
          return a.category.localeCompare(b.category);
        default:
          return 0;
      }
    });

    return filtered;
  }, [issues, searchText, selectedSeverity, selectedCategory, sortBy]);

  // 统计信息
  const statistics = useMemo(() => {
    const stats = {
      total: issues.length,
      high: issues.filter(i => i.severity === 'HIGH').length,
      medium: issues.filter(i => i.severity === 'MEDIUM').length,
      low: issues.filter(i => i.severity === 'LOW').length,
      info: issues.filter(i => i.severity === 'INFO').length,
      categories: {} as Record<ProblemCategory, number>
    };

    // 统计分类
    issues.forEach(issue => {
      stats.categories[issue.category] = (stats.categories[issue.category] || 0) + 1;
    });

    return stats;
  }, [issues]);

  // 处理问题项点击
  const handleIssueClick = (issue: CompatibilityIssue) => {
    if (onIssueClick) {
      onIssueClick(issue);
    }
  };

  // 渲染过滤器
  const renderFilters = () => {
    if (!enableFiltering) return null;

    return (
      <Card size="small" style={{ marginBottom: 16 }}>
        <Row gutter={[8, 8]} align="middle">
          <Col xs={24} sm={12} md={8}>
            <Search
              placeholder="搜索问题..."
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              size="small"
              allowClear
            />
          </Col>
          <Col xs={12} sm={6} md={4}>
            <Select
              placeholder="严重程度"
              value={selectedSeverity}
              onChange={setSelectedSeverity}
              size="small"
              style={{ width: '100%' }}
            >
              <Option value="ALL">全部</Option>
              <Option value="HIGH">高危</Option>
              <Option value="MEDIUM">中危</Option>
              <Option value="LOW">低危</Option>
              <Option value="INFO">提示</Option>
            </Select>
          </Col>
          <Col xs={12} sm={6} md={4}>
            <Select
              placeholder="问题分类"
              value={selectedCategory}
              onChange={setSelectedCategory}
              size="small"
              style={{ width: '100%' }}
            >
              <Option value="ALL">全部</Option>
              <Option value="SYNTAX">语法</Option>
              <Option value="FUNCTION">函数</Option>
              <Option value="DATATYPE">数据类型</Option>
              <Option value="PERFORMANCE">性能</Option>
              <Option value="COMPATIBILITY">兼容性</Option>
            </Select>
          </Col>
          {enableSorting && (
            <Col xs={24} sm={24} md={8}>
              <Space>
                <Text type="secondary" style={{ fontSize: 12 }}>排序:</Text>
                <Select
                  value={sortBy}
                  onChange={setSortBy}
                  size="small"
                  style={{ width: 100 }}
                >
                  <Option value="severity">严重程度</Option>
                  <Option value="line">行号</Option>
                  <Option value="category">分类</Option>
                </Select>
              </Space>
            </Col>
          )}
        </Row>
      </Card>
    );
  };

  // 渲染统计信息
  const renderStatistics = () => (
    <div style={{ marginBottom: 16, padding: '8px 12px', background: '#fafafa', borderRadius: 6 }}>
      <Row gutter={16} align="middle">
        <Col>
          <Text type="secondary" style={{ fontSize: 12 }}>
            显示 {filteredAndSortedIssues.length} / {statistics.total} 个问题
          </Text>
        </Col>
        <Col>
          <Space size={8}>
            {statistics.high > 0 && (
              <Badge count={statistics.high} color="#ff4d4f" title="高危问题" />
            )}
            {statistics.medium > 0 && (
              <Badge count={statistics.medium} color="#faad14" title="中危问题" />
            )}
            {statistics.low > 0 && (
              <Badge count={statistics.low} color="#1890ff" title="低危问题" />
            )}
            {statistics.info > 0 && (
              <Badge count={statistics.info} color="#52c41a" title="提示信息" />
            )}
          </Space>
        </Col>
      </Row>
    </div>
  );

  // 处理规则名称点击
  const handleRuleNameClick = (ruleId: string | undefined, event: React.MouseEvent) => {
    event.stopPropagation(); // 阻止卡片点击事件
    if (ruleId && ruleId !== 'AI001' && !ruleId.startsWith('AI')) {
      setSelectedRuleId(ruleId);
      setRuleDetailVisible(true);
    }
  };

  // 关闭规则详情模态框
  const handleRuleDetailClose = () => {
    setRuleDetailVisible(false);
    setSelectedRuleId(null);
  };

  // 渲染问题列表项
  const renderIssueItem = (issue: CompatibilityIssue) => {
    const { icon, color } = getSeverityIcon(issue.severity);
    const categoryIcon = getCategoryIcon(issue.category);

    return (
      <List.Item
        key={issue.id}
        className="problem-list-item"
        onClick={() => handleIssueClick(issue)}
      >
        <Card
          size="small"
          hoverable
          style={{ width: '100%', cursor: 'pointer' }}
          bodyStyle={{ padding: '12px 16px' }}
        >
          <div style={{ display: 'flex', gap: 12 }}>
            {/* 严重程度图标 */}
            <Avatar
              size={40}
              style={{ backgroundColor: color, flexShrink: 0 }}
              icon={icon}
            />
            
            {/* 问题内容 */}
            <div style={{ flex: 1, minWidth: 0 }}>
              {/* 标题行 */}
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                {issue.ruleId && issue.ruleId !== 'AI001' && !issue.ruleId.startsWith('AI') ? (
                  <Button
                    type="link"
                    onClick={(e) => handleRuleNameClick(issue.ruleId, e)}
                    style={{
                      padding: 0,
                      height: 'auto',
                      fontSize: 14,
                      fontWeight: 'bold',
                      marginRight: 8,
                      textAlign: 'left'
                    }}
                  >
                    {issue.ruleName}
                  </Button>
                ) : (
                  <Text strong style={{ fontSize: 14, marginRight: 8 }}>
                    {issue.ruleName}
                  </Text>
                )}
                
                <Space size={4}>
                  <Tag color={color}>
                    {issue.severity}
                  </Tag>
                  
                  <Tooltip title={`问题分类: ${issue.category}`}>
                    <Tag icon={categoryIcon}>
                      {issue.category}
                    </Tag>
                  </Tooltip>
                  
                  {issue.analysisSource && (
                    <Tooltip title={`分析来源: ${issue.analysisSource === 'RULE' ? '规则分析' : 'AI分析'}`}>
                      <Tag 
                        icon={issue.analysisSource === 'RULE' ? <SettingOutlined /> : <RobotOutlined />}
                        color={issue.analysisSource === 'RULE' ? 'blue' : 'purple'}
                      >
                        {issue.analysisSource === 'RULE' ? '规则' : 'AI'}
                      </Tag>
                    </Tooltip>
                  )}
                  
                  {/* AI验证状态标识 */}
                  {issue.ruleAnalysisConfirmed !== undefined && (
                    <Tooltip title={
                      issue.ruleAnalysisConfirmed 
                        ? `AI确认此问题确实存在 (置信度: ${issue.aiConfidenceScore ? Math.round(issue.aiConfidenceScore * 100) : 'N/A'}%)` 
                        : 'AI认为此问题可能不存在或不重要'
                    }>
                      <Tag 
                        color={issue.ruleAnalysisConfirmed ? 'red' : 'cyan'} 
                        style={{ fontSize: '10px' }}
                      >
                        {issue.ruleAnalysisConfirmed ? 'AI确认' : 'AI质疑'}
                      </Tag>
                    </Tooltip>
                  )}
                  
                  {issue.confidence && (
                    <Tooltip title={`置信度: ${Math.round(issue.confidence * 100)}%`}>
                      <Tag color="green">
                        {Math.round(issue.confidence * 100)}%
                      </Tag>
                    </Tooltip>
                  )}
                </Space>
              </div>
              
              {/* 问题描述 */}
              <Paragraph 
                style={{ margin: 0, fontSize: 13, color: '#595959', marginBottom: 8 }}
                ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
              >
                {issue.description}
              </Paragraph>
              
              {/* 位置信息 */}
              {showLineNumbers && (
                <div style={{ marginBottom: 8 }}>
                  <Space size={8}>
                    <Tooltip title="点击跳转到代码位置">
                      <Tag 
                        icon={<EnvironmentOutlined />} 
                        color="default"
                        style={{ cursor: 'pointer' }}
                      >
                        行 {issue.lineNumber}:{issue.columnNumber}
                      </Tag>
                    </Tooltip>
                    
                    {issue.fileName && (
                      <Text type="secondary" style={{ fontSize: 11 }}>
                        {issue.fileName}
                      </Text>
                    )}
                  </Space>
                </div>
              )}
              
              {/* 修复建议 */}
              {issue.suggestion && (
                <div style={{ 
                  padding: '6px 8px', 
                  background: '#f0f9ff', 
                  borderRadius: 4,
                  borderLeft: '3px solid #1890ff'
                }}>
                  <Text style={{ color: '#1890ff', fontSize: 12 }}>
                    <BulbOutlined style={{ marginRight: 4 }} />
                    {issue.suggestion}
                  </Text>
                </div>
              )}
            </div>
          </div>
        </Card>
      </List.Item>
    );
  };

  // 如果没有问题
  if (issues.length === 0) {
    return (
      <Card>
        <Empty
          image={<CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a' }} />}
          description={
            <div>
              <div>未发现兼容性问题</div>
              <Text type="secondary" style={{ fontSize: 12 }}>
                SQL语句在目标数据库中可以正常运行
              </Text>
            </div>
          }
        />
      </Card>
    );
  }

  return (
    <div className="problem-list">
      {renderFilters()}
      {renderStatistics()}
      
      <div style={{ maxHeight, overflow: 'auto' }}>
        {filteredAndSortedIssues.length === 0 ? (
          <Empty
            description="没有找到匹配的问题"
            style={{ padding: '40px 0' }}
          />
        ) : (
          <List
            dataSource={filteredAndSortedIssues}
            renderItem={renderIssueItem}
            split={false}
            style={{ gap: 8 }}
          />
        )}
      </div>

      {/* 规则详情模态框 */}
      <RuleDetailModal
        visible={ruleDetailVisible}
        ruleId={selectedRuleId}
        onClose={handleRuleDetailClose}
      />
    </div>
  );
};

export default ProblemList;